package org.yyj.dao.impl;

import org.yyj.dao.XsDao;
import org.yyj.factory.*;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import org.yyj.model.Xsb;

public class XsDaoImp implements XsDao {

    @Override
    //获取指定学号的某个学生的信息
    public Xsb getOneXs(String xh) {
        try{
            /*//创建Configuration
            Configuration configuration=new
                    Configuration().configure("hibernate.cfg.xml");
            //获取SessionFactory
            SessionFactory sessionFactory=configuration.buildSessionFactory();
            //获取Session
            Session session=sessionFactory.openSession();*/
            Session session= HibernateSessionFactory.getSession();
            //开启事务
            Transaction transaction=session.beginTransaction();
            Query query=session.createQuery("from Xsb where xh=?");
            query.setParameter(0,xh);
            query.setMaxResults(1);
            Xsb xs=(Xsb) query.uniqueResult(); //执行查询 返回结果 指定学号的学生
            transaction.commit();
            session.clear();
            return xs;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }

    @Override
    //修改某个学生的个人信息
    public void update(Xsb xs) {
        try {
            //创建Configuration
            Configuration configuration=new
                    Configuration().configure("hibernate.cfg.xml");
            //获取SessionFactory
            SessionFactory sessionFactory=configuration.buildSessionFactory();
            //获取Session
            Session session=sessionFactory.openSession();
            /*Session session= HibernateFactory.getSession();*/
            //开启事务
            Transaction transaction=session.beginTransaction();
            session.update(xs);     //执行修改操作
            transaction.commit();   //事务提交

            session.close();        //关闭会话

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
